
#include <stdio.h>
#include <stdlib.h>


int bin2hex(FILE* in, FILE* out)
{
	char buffer[4096];
	int i, n;
	char table[16] = {'0', '1', '2', '3', '4', '5', '6', '7',
			  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
	char stable[16] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
	                   ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\n'};

	

	while( (n = fread(buffer, 1, sizeof(buffer), in)) > 0 )
	{
		for(i = 0; i < n; ++i)
		{
			int a = (buffer[i]>>4)&0x0F;
			int b = buffer[i]     &0x0F;
			fputc(table[a], out);
			fputc(table[b], out);
			fputc(stable[i&0x0F], out);
		}
	}

	return 0;
}

int main(int argc, char** argv)
{
	FILE* in;
	FILE* out;

	if(argc==3)
	{
		in = fopen(argv[1], "rb");
		out = fopen(argv[2], "w");
	}
	else if(argc==1)
	{
		in = stdin;
		out = stdout;
	}
	else if(argc==2)
	{
		in = fopen(argv[1], "rb");
		out = stdout;
	}
	else
	{
		fprintf(stderr, "usage: bin2hex input output\n");
		return 1;
	}


	bin2hex(in, out);

	return 0;
}

